// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
let dbJQL
const db = uniCloud.database();
const dbCmd = db.command
const dbColCategory = db.collection('todo-category')
const dbColTodo = db.collection('todo-list')

// 按照id title查找数据
const findByTitle = async (arrObj) => {
	let arr = []
	for (let i = 0; i < arrObj.length; i++) {
		const res = await dbColCategory.where({
			_id: arrObj[i]._id,
			title: arrObj[i].title,
		}).count()
		if (res.total == 0) {
			arr.push(arrObj[i])
		}
	}
	return arr
}

// 获取分组数据
const getCategory = async (limit = 10) => {
	// let res = await db.collection('my-music-backup').doc(event.id).update({
	let res = await dbColCategory
		.where({
			title: dbCmd.neq(null)
		})
		.orderBy("updateTime", "desc").limit(20).get()
	//返回数据给客户端
	return {
		code: 0,
		message: '访问成功',
		data: res.data
	}
}

// 添加分组数据
const addCategory = async (dataObj) => {
	const res = await dbColCategory.add(dataObj) // 直接执行数据库操作
	return {
		code: 0,
		message: '执行插入成功',
		data: res
	}
}

// 删除分组数据
const delCategory = async (id) => {
	let res = await dbColCategory.doc(id).remove()
	if (res.affectedDocs == 0) {
		return {
			code: 1,
			message: '删除失败',
			data: res
		}
	}
	return {
		code: 0,
		message: '执行删除成功',
		data: res
	}
}
// 更新分组数据
const updateCategory = async (dataObj) => {
	const {
		_id,
		title
	} = dataObj
	let res = await dbColCategory.doc(_id).update({
		title
	})
	if (res.updated == 0) {
		return {
			code: 1,
			message: '更新失败',
			data: res
		}
	}
	return {
		code: 0,
		message: '更新成功',
		data: res
	}
}
// 添加todo
const addTodo = async (dataObj) => {
	const res = await dbColTodo.add(dataObj) // 直接执行数据库操作
	return {
		code: 0,
		message: '执行插入成功',
		data: res
	}
}

// 删除todo
const delTodo = async (id) => {
	let res = await dbColTodo.doc(id).remove()
	if (res.affectedDocs == 0) {
		return {
			code: 1,
			message: '删除失败',
			data: res
		}
	}
	return {
		code: 0,
		message: '执行删除成功',
		data: res
	}
}

// 更新todo数据
const updateTodo = async (dataObj) => {
	const {
		_id,
		title,
		status
	} = dataObj
	let res = await dbColTodo.doc(_id).update({
		title,
		status
	})
	if (res.updated == 0) {
		return {
			code: 1,
			message: '更新失败',
			data: res
		}
	}
	return {
		code: 0,
		message: '更新成功',
		data: res
	}
}
module.exports = {
	_before: function() { // 通用预处理器
		dbJQL = uniCloud.databaseForJQL({ // 获取JQL database引用，此处需要传入云对象的clientInfo
			clientInfo: this.getClientInfo()
		})
	},
	getCategory,
	findByTitle,
	addCategory,
	delCategory,
	updateCategory,
	addTodo,
	delTodo,
	updateTodo,
	_after(error, result) {
		if (error) {
			// throw error // 如果方法抛出错误，也直接抛出不处理
			return {
				code: 1,
				message: '执行失败',
				data: error
			}
		}
		// result.timeCost = Date.now() - this.startTime
		return result
	}

}
